var MyState=null;
var TimerState=null;
var OpensimInstanceDnsName = null;
var NewVolumeId = null;
var xhrhandle;
var shutsimXHR;
var TimerCount = 0;
var InstanceState = null;
var OnlyRestUrl = null;
var ec2RestUrl = null;

 // Now it is time to create the timer...  
var Timer = Components.classes["@mozilla.org/timer;1"]
       .createInstance(Components.interfaces.nsITimer);
 
 // ... and to initialize it, we want to call event.notify() ...
 // ... one time after exactly ten second. 

function state_StatusUrl()
{
	Dbg('state_StatusUrl');
   try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
   } catch (e) {
    Dbg("Permission UniversalBrowserRead denied.");
   }

	if (xhrhandle.readyState==4)
	  {// 4 = "loaded"
	  if (xhrhandle.status==200)
	    {// 200 = OK
	    // ...our code here...
	       try {
		    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		   } catch (e) {
		    alert("Permission UniversalBrowserRead denied.");
		   }
	
	    Dbg('status=200 Ok');
	    // Make it into a JSON for server side status. 
	    /*
	    x=xhrhandle.responseXML.documentElement.getElementsByTagName('UniqueName');
	    SimOnDemandSettings.UniqueId = x[0].firstChild.nodeValue;
  	    x=xhrhandle.responseXML.documentElement.getElementsByTagName('Volume');
  	    
	    if ( x[0].firstChild.nodeValue == 'mounted')
	    {
	    	Dbg('Volume=mounted - setting TimerState to Normal');
	    	TimerState = 'Normal';
	    }

	    saveSettingsToFile();
	    **/
	    TimerState == 'Normal';
	    // Check if the volume is attached. If not attach volume.
	    
	    }
	  else
	    {
	    Dbg("Problem retrieving XML data");
	    }
	  }
}
function invokeStatusUrl(url, handler)
{
	Dbg('invokeStatusUrl url=' + url);
   try {
	    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	   } catch (e) {
	    alert("Permission UniversalBrowserRead denied.");
	   }

	xhrhandle=null;
	if (window.XMLHttpRequest)
	  {// code for all new browsers
	  xhrhandle=new XMLHttpRequest();
	  }
	else if (window.ActiveXObject)
	  {// code for IE5 and IE6
	  xhrhandle=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	if (xhrhandle!=null)
	  {
	  xhrhandle.onreadystatechange=handler;
	  xhrhandle.open("GET",url,true);
	  xhrhandle.send(null);
	  }
	else
	  {
	  alert("Your browser does not support XMLHTTP.");
	  }
}


function saveKeyToFile(keyName, keyMaterial) {

	Dbg('saveKeyToFile');

	var keyfile = keyName + '.pem';
	var output = keyMaterial;
	
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	} catch (e) {
		alert("Permission to save file was denied.");
	}
	// get the path to the user's home (profile) directory
	const DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1","nsIProperties");
	try { 
		path=(new DIR_SERVICE()).get("ProfD", Components.interfaces.nsIFile).path; 
	} catch (e) {
		alert("error");
	}
	// determine the file-separator
	if (path.search(/\\/) != -1) {
		path = path + "\\";
	} else {
		path = path + "/";
	}
	keyfile = path+keyfile;

	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
	} catch (e) {
		alert("Permission to save file was denied.");
	}
	var file = Components.classes["@mozilla.org/file/local;1"]
		.createInstance(Components.interfaces.nsILocalFile);
	file.initWithPath( keyfile );
	if ( file.exists() == false ) {
		//alert( "Creating file... " );
		file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 400 );
	}
	var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
		.createInstance( Components.interfaces.nsIFileOutputStream );
	/* Open flags 
	#define PR_RDONLY       0x01
	#define PR_WRONLY       0x02
	#define PR_RDWR         0x04
	#define PR_CREATE_FILE  0x08
	#define PR_APPEND      0x10
	#define PR_TRUNCATE     0x20
	#define PR_SYNC         0x40
	#define PR_EXCL         0x80
	*/
	/*
	** File modes ....
	**
	** CAVEAT: 'mode' is currently only applicable on UNIX platforms.
	** The 'mode' argument may be ignored by PR_Open on other platforms.
	**
	**   00400   Read by owner.
	**   00200   Write by owner.
	**   00100   Execute (search if a directory) by owner.
	**   00040   Read by group.
	**   00020   Write by group.
	**   00010   Execute by group.
	**   00004   Read by others.
	**   00002   Write by others
	**   00001   Execute by others.
	**
	*/
	
	//outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
	outputStream.init( file, 0x04 | 0x08 | 0x20, 660, 0 );
	var result = outputStream.write( output , output.length );
	outputStream.close();

}
var 	CDIRCount = 5; // Number of CDIR entries to tally
function authorizeSourceCIDRStatus()
{
	CDIRCount--;
	Dbg('authorizeSourceCIDRStatus CDIRCount = ' + CDIRCount);
	if ( CDIRCount == 0)
		{
			Dbg('authorizeSourceCIDRStatus: progressing to next');
			saveSettingsToFile();
			InferState();
			return;
		}
}
function createSecurityGroupStatus()
{
	Dbg('createSecurityGroupStatus');
	ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );

	ec2ui_controller.authorizeSourceCIDR(SimOnDemandSettings.securityGroups,
		"tcp",22, 22,"0.0.0.0/0",  authorizeSourceCIDRStatus);
	ec2ui_controller.authorizeSourceCIDR(SimOnDemandSettings.securityGroups,
		"tcp",80, 80,"0.0.0.0/0",  authorizeSourceCIDRStatus);
	ec2ui_controller.authorizeSourceCIDR(SimOnDemandSettings.securityGroups,
		"tcp",9000, 9009,"0.0.0.0/0",  authorizeSourceCIDRStatus);
	ec2ui_controller.authorizeSourceCIDR(SimOnDemandSettings.securityGroups,
		"udp",9000, 9009,"0.0.0.0/0",  authorizeSourceCIDRStatus);
	ec2ui_controller.authorizeSourceCIDR(SimOnDemandSettings.securityGroups,
		"tcp",9080, 9080,"0.0.0.0/0",  authorizeSourceCIDRStatus);


}
function describeSecurityGroupsStatus(list)
{
	Dbg('describeSecurityGroupsStatus');

	var keyIndex=null;
	for (var k in list )
	{
		Dbg('list[k].name=' + list[k].name + 'ownerid=' + list[k].ownerId);
		if (list[k].name == SimOnDemandSettings.securityGroups)
			keyIndex = k;	
	}
	
	if( keyIndex == null) // No matching keyName found. Create one.
	{
		if( SimOnDemandSettings.securityGroups == null || SimOnDemandSettings.securityGroups == "")
			SimOnDemandSettings.securityGroups = "SimOnDemandSG"; 
		Dbg('describeSecurityGroupsStatus initiating creation of SecGrp:' + SimOnDemandSettings.securityGroups );
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.createSecurityGroup(SimOnDemandSettings.securityGroups,"SimOnDemand OpenSim OpenPorts", createSecurityGroupStatus);

	}
	else // SecurityGroup matching the setting is found. Go to next state.
	{
		Dbg('describeSecurityGroupsStatus:' +  list[keyIndex].name + ' found, progressing');
		saveSettingsToFile();
		InferState();
		return;
	}

}

function createKeypairStatus(name, keyMaterial)
{
		Dbg('createKeypairStatus'); // Keypair matching the setting created. Save and move to Next state.
		saveKeyToFile(name, keyMaterial);
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.describeSecurityGroups(describeSecurityGroupsStatus);
		return;
}
function describeKeyPairsStatus(list)
{
	Dbg('describeKeyPairsStatus');
	Dbg('Verification success!');

	var keyIndex=null;
	for (var k in list )
	{
		Dbg('list[k].name=' + list[k].name);
		if (list[k].name == SimOnDemandSettings.keyName)
			keyIndex = k;	
	}
	
	if( keyIndex == null) // No matching keyName found. Create one.
	{
		if( SimOnDemandSettings.keyName == null || SimOnDemandSettings.keyName == "")
			SimOnDemandSettings.keyName = "SimOnDemand-key"; 
		Dbg('describeKeyPairsStatus initiating creation of KeyPair:' + SimOnDemandSettings.keyName );
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.createKeypair(SimOnDemandSettings.keyName, createKeypairStatus);

	}
	else // keyName matching the setting is found. Go to next state.
	{
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.describeSecurityGroups(describeSecurityGroupsStatus);
		return;
	}
	
}

function describeLaunchPermissionsStatus(list)
{
	Dbg('describeLaunchPermissionsStatus');
	Dbg('Verification success!');


	ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
	ec2ui_controller.describeKeypairs(describeKeyPairsStatus);


}
function verifyCred()
{


	Dbg('verifyCred');
	transitionVisual();
// Do a describe images based on the access key, secret key pair 
// if hte describe image returns proper results, then the credentials are ok.
// save it in the file and then call infer state.
	Dbg('Verifying...');
	ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
	ec2ui_controller.describeKeypairs(describeKeyPairsStatus);


}
// remove multiple, leading or trailing spaces
function trim(s) {
	s = s.replace(/(^\s*)|(\s*$)/gi,"");
	s = s.replace(/[ ]{2,}/gi," ");
	s = s.replace(/\n /,"\n");
	return s;
}
function setAWSAccessKeyId()
{
	Dbg('setAWSAccessKeyId');
	SimOnDemandSettings.AWSAccessKeyId = trim(document.getElementById("AWSAccessKeyId").value);
	Dbg(SimOnDemandSettings.AWSAccessKeyId);
}
function setAWSSecretAccessKey()
{
	Dbg('setAWSSecretAccessKey');
	SimOnDemandSettings.AWSSecretAccessKey = trim(document.getElementById("AWSSecretAccessKey").value);
	Dbg(SimOnDemandSettings.AWSSecretAccessKey);
}
function setKeyName()
{
	Dbg('setKeyName');
	SimOnDemandSettings.keyName = document.getElementById("keyName").value;
	Dbg(SimOnDemandSettings.keyName);
}
function promptSettings()
{
	document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:verifyCred();\"><img   border=\"0\" src=\"images/button-settings.png\"></a>";
	                             
	document.getElementById("InfoArea").innerHTML = "<input onblur=\"if (this.value == '') this.value='AWS Access Key ID'\" \
	onclick=\"this.select();\" \
	onchange=\"setAWSAccessKeyId();\" style=\"border: 1px solid rgb(102, 153, 204); height: 20px; color: rgb(0, 102, 153); font-size: 13px; width: 135px;\" value=\"AWS Access Key Id\" id=\"AWSAccessKeyId\" name=\"AWSAccessKeyId\" type=\"text\">&nbsp;&nbsp; \
	<input onblur=\"if (this.value == '') this.value='AWS Secret Key'\" \
	onclick=\"this.select();\" \
	onchange=\"setAWSSecretAccessKey();\" style=\"border: 1px solid rgb(102, 153, 204); height: 20px; color: rgb(0, 102, 153); font-size: 13px; width: 135px;\" value=\"AWS Secret Key\" id=\"AWSSecretAccessKey\" name=\"AWSSecretAccessKey\" type=\"text\"> <br><br> \
	<input onblur=\"if (this.value == '') this.value='Key Pair Id(Optional)'\" \
	onclick=\"this.select();\" \
	onchange=\"setKeyName();\" style=\"border: 1px solid rgb(102, 153, 204); height: 20px; color: rgb(0, 102, 153); font-size: 13px; width: 135px;\" value=\"Key Pair Id(Optional) \" id=\"keyName\" name=\"keyName\" type=\"text\">" 
	+ "<br><br><a href=\"javascript:verifyCred();\"><img   border=\"0\" src=\"images/go.gif\"></a>";
	document.getElementById("AWSAccessKeyId").focus();
	document.getElementById("AWSAccessKeyId").select();
}

function InferState()
{
	//Infer the state
	/* 
	** Check if the credentials are valid
	** If VolumeId == None StartAfresh
	** If VolumeId != None and InstanceId Alive => Alive
	** If VolumeId != None and Instance Not Alive => Restart
	*/
	Dbg('InferState');
	if( SimOnDemandSettings.UniqueId == "None" && SimOnDemandSettings.instanceId == "None")
	{
		MyState= "StartAfresh";
		Dbg('InferState:MyState = ' + MyState);
		document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-launch.png\"></a>";
		document.getElementById("InfoArea").innerHTML = "<h4>Click Launch to Start OpenSim on EC2</h4>";
		return ;
	}
	CheckInstanceStatus();
	

	if( SimOnDemandSettings.instanceId != "None")
	{
		MyState = "Alive";
		Dbg('InferState:MyState = ' + MyState);
		if(OpensimInstanceDnsName)
		{
			document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-pause.png\"></a>";
			document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-pause.png\"></a>";
			document.getElementById("InfoArea").innerHTML = "Opensim Instance " + OpensimInstanceDnsName + " Ready<br>"
				+ "You can access the Opensim by appending<br><strong><tt> -loginuri http://" + OpensimInstanceDnsName + ":9000 </strong></tt>" + "<br>to SecondLife Client Shortcut<br><br>"
				+ "<h4>Press Pause to Pause Running Instance</h4>";
	
		}
		else // 
		{
				document.getElementById("InfoArea").innerHTML = "<h4>Waiting for EC2 instance to be ready...<br> DO NOT Refresh!!!</h4>";
		}

		TimerState = 'Transition';
		Timer.initWithCallback(
			eventInstanceReady,
			120000,
			Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
		
		return ;
		
	}
	else
	{
		MyState = "Restart";
		Dbg('InferState:MyState = ' + MyState);
		document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-launch.png\"></a>";
		document.getElementById("InfoArea").innerHTML ="<h4>Click Launch to resume OpenSim Instance </h4>";
		return ;
	}
}
function describeInstanceStatus(list)
{
	var instanceIndex=-1;
	for (var k in list )
	{	
	if ( SimOnDemandSettings.instanceId == list[k].id && 
			(list[k].state == "running" || list[k].state == "pending" ))
		{
			instanceIndex = k;
			Dbg("InstanceStatus:InstanceId = " + list[k].id);
			//Freshly running instance
			OpensimInstanceDnsName = list[k].publicDnsName;

			if (list[k].state == "running" )
				{
					if(InstanceState == 'pending') // The instance has just transitioned from pending to running
					{
						// Code to attach volume

						InstanceState = list[k].state;
						Dbg('describeInstanceStatus: attaching volume');
						ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
						var result = ec2ui_controller.attachVolume(SimOnDemandSettings.UniqueId, SimOnDemandSettings.instanceId, "/dev/sdh", attachVolumeStatus);
						if ( result == false )
							alert('Attaching Elastic Block Store(EBS) fail manual attach recommended');


					}
					invokeStatusUrl('http://' + list[k].publicDnsName + ':9080/status', state_StatusUrl); 
				}
		}
	}
	/**
	** If instanceId not alive, invalidate it.
	**/ 
	if( instanceIndex == -1)
	{
		Dbg('setting InstanceId=None');
		SimOnDemandSettings.instanceId = "None";
		OpensimInstanceDnsName = null;
		saveSettingsToFile();
		Timer.cancel();
	}
}

function CheckInstanceStatus()
{
// ToDo: Put a timer/counter based 

	 if( SimOnDemandSettings.instanceId != "None")
		{
		
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.describeInstances(describeInstanceStatus);
		}

}

var eventInstanceReady = 
	{
		notify: function(timer)
			{
				Dbg('eventInstanceReady notify');
				if( TimerState == 'Normal')
					{
						Dbg('Adjusting Timer to Normal Mode');
						Timer.initWithCallback(
							eventInstanceReady,
							300000,
							Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);

					}
				CheckInstanceStatus();
			} 
								 
	};
 
function attachVolumeStatus(objResponse)
{
	Dbg('attachVolumeStatus');

   var xmlDoc = objResponse.xmlDoc;
   try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
		alert("Permission UniversalBrowserRead denied.");
	}

	var volumeId = xmlDoc.getElementsByTagName("volumeId")[0].firstChild.nodeValue;
	var status = xmlDoc.getElementsByTagName("status")[0].firstChild.nodeValue;
	if(status == 'attached')
	{
		Dbg('attachVolumeStatus status attached yay!');

	}
	else
	{
			Dbg('attachVolumeStatus status not attached yet What now?');
	}
	TimerState == 'Normal';
	if(OpensimInstanceDnsName)
	{
		document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-pause.png\"></a>";
		document.getElementById("ControlArea").innerHTML = "<a href=\"javascript:OnClickControl();\"><img   border=\"0\" src=\"images/button-pause.png\"></a>";
		document.getElementById("InfoArea").innerHTML = "Opensim Instance " + OpensimInstanceDnsName + " Ready<br>"
			+ "You can access the Opensim by appending<br><strong><tt> -loginuri http://" + OpensimInstanceDnsName + ":9000 </strong></tt>" + "<br>to SecondLife Client Shortcut<br><br>"
			+ "<h4>Press Pause to Pause Running Instance</h4>";

	}
}
function runInstanceStatus(list)
{
	Dbg('runInstanceStatus' + list[0].id);
	SimOnDemandSettings.instanceId = list[0].id;
	if(list[0].state == 'running') // Attach the volume
	{
		Dbg('runInstanceStatus: attaching volume');
		InstanceState = list[0].state;		
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		var result = ec2ui_controller.attachVolume(SimOnDemandSettings.UniqueId, SimOnDemandSettings.instanceId, "/dev/sdh", attachVolumeStatus);
		if ( result == false )
			alert('Attaching Elastic Block Store(EBS) fail manual attach recommended');
	}
	else
	{
		InstanceState = list[0].state;
		Dbg('runInstanceStatus setting InstanceState to ' + InstanceState);
	}
	saveSettingsToFile();
	transitionVisual();	
	document.getElementById("InfoArea").innerHTML = "<h4>Waiting for EC2 instance to be ready...<br> DO NOT Refresh!!!</h4>";
	
	TimerState = 'Transition';
	Timer.initWithCallback(
		eventInstanceReady,
		50000,
		Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
}

function describeVolumesStatus(list)
{
	Dbg('describeVolumesStatus');
	var instanceIndex=-1;
	for (var k in list )
	{	
	if ( SimOnDemandSettings.UniqueId == list[k].id )
		{
			instanceIndex = k;
			Dbg("describeVolumesStatus:volumeId = " + list[k].volumeId);
			// Check if the status is available 
			if ( list[k].status == "available")
			{
				// Everything is fine proceed ahead
			
			   var userData = 'StartAfresh=0' +
			   		' | Email=' + SimOnDemandSettings.Email +  
						' | InitBucket=' + SimOnDemandSettings.InitBucket +
			   		' | UniqueName=' + SimOnDemandSettings.UniqueId;
				ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
				ec2ui_controller.runInstances(
				SimOnDemandSettings.imageId,
				 null,
				 null,
				 SimOnDemandSettings.minCount,
				 SimOnDemandSettings.maxCount,
				 SimOnDemandSettings.keyName,
				 [SimOnDemandSettings.securityGroups],
				 userData,
				 null,
				 SimOnDemandSettings.instanceType,
				 SimOnDemandSettings.placement,
				 runInstanceStatus); 
			}
			else
			{
					Dbg('Volume status not ok. restore from snapshot');
					alert('ErrorVolume status= ' + list[k].status + ' not ok. manual restore from snapshot recommended');

			}
			
		}					// Check if the volume is attached. If not attach volume.
	}

	if( instanceIndex == -1)
	{
		// The volume somehow got deleted. 
		Dbg('Volume got deleted. restore from snapshot');
		alert('Volume got deleted. restore from snapshot');
	}

}
function createVolumeStatus(objResponse)
{
	Dbg('createVolumeStatus');

   var xmlDoc = objResponse.xmlDoc;
   try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
		alert("Permission UniversalBrowserRead denied.");
	}

	var volumeId = xmlDoc.getElementsByTagName("volumeId")[0].firstChild.nodeValue;
	SimOnDemandSettings.UniqueId = volumeId;

   var userData = 'StartAfresh=1' + '| Email=' + SimOnDemandSettings.Email +  
   										' | InitBucket=' + SimOnDemandSettings.InitBucket +
   										' | UniqueName=' + SimOnDemandSettings.UniqueId;

	ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
	ec2ui_controller.runInstances(
	SimOnDemandSettings.imageId,
	 null,
	 null,
	 SimOnDemandSettings.minCount,
	 SimOnDemandSettings.maxCount,
	 SimOnDemandSettings.keyName,
	 [SimOnDemandSettings.securityGroups],
	 userData,
	 null,
	 SimOnDemandSettings.instanceType,
	 SimOnDemandSettings.placement,
	 runInstanceStatus); 

}


function runOpensimInstance()
{
	Dbg('runOpensimInstance');

	// Create describe volume first
	if ( SimOnDemandSettings.UniqueId == "None")
	{
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.createVolume(10,null, SimOnDemandSettings.placement.availabilityZone,createVolumeStatus );
		// TODO: Remove the hardcoding of volumeSize above
	}
	else 
	{
		ec2_httpclient.setCredentials(getAccessKeyId(), getSecretAccessKey() );
		ec2ui_controller.describeVolumes(describeVolumesStatus);
	} 

}

function terminateInstanceStatus(list)
{
	Dbg('Terminate Instance returns');
	SimOnDemandSettings.instanceId = "None";
	reloadMe();	
	
}

function ShutSimStatus()
{
	Dbg('state_StatusUrl');
   try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
   } catch (e) {
    Dbg("Permission UniversalBrowserRead denied.");
   }

	if (shutsimXHR.readyState==4)
	  {// 4 = "loaded"
	  if (shutsimXHR.status==200)
	    {// 200 = OK
	    // ...our code here...
	       try {
		    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
		   } catch (e) {
		    alert("Permission UniversalBrowserRead denied.");
		   }
	
		 Dbg('ShutSimStatus: status=200 Ok');
					var list = new Array();
					list[0] = SimOnDemandSettings.instanceId;
				
					ec2ui_controller.terminateInstances(
						list, 
						terminateInstanceStatus);
	    TimerState == 'Normal';
	    // Check if the volume is attached. If not attach volume.
	    
	    }
	  else
	    {
	    Dbg("Problem retrieving XML data");
	    }
	  }
}
function invokeShutsimUrl(url, handler)
{
	Dbg('invokeShutsimUrl url=' + url);
   try {
	    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	   } catch (e) {
	    alert("invokeShutsimUrl: Permission UniversalBrowserRead denied.");
	   }

	shutsimXHR=null;
	if (window.XMLHttpRequest)
	  {// code for all new browsers
	  shutsimXHR=new XMLHttpRequest();
	  }
	else if (window.ActiveXObject)
	  {// code for IE5 and IE6
	  shutsimXHR=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	if (shutsimXHR!=null)
	  {
	  shutsimXHR.onreadystatechange=handler;
	  shutsimXHR.open("GET",url,true);
	  shutsimXHR.send(null);
	  }
	else
	  {
	  alert("invokeShutsimUrl: Your browser does not support XMLHTTP.");
	  }
}



function terminateOpensimInstance()
{
	
	// Before terminating, the opensim must be shutdown, mysql stopped, volume detached.
	// This is done by invoking the small http server running on the instance that expects
	// shutsim url invocation.
	// A rest call to invoke the detach volume is to be supplied too. 
	Dbg('terminateOpensimInstance');
	
	Timer.cancel();
	transitionVisual();	
	document.getElementById("InfoArea").innerHTML = "<h4>Shutding down Opensim and EC2 instance...<br> </h4>";

	Dbg('terminateOpensimInstance');	

	OnlyRestUrl = 1;
	ec2ui_controller.detachVolume(SimOnDemandSettings.UniqueId, null); 
	OnlyRestUrl = null;
	var detachvolurl = ec2RestUrl;
	Dbg('terminateOpensimInstance: calling invokeShutsimUrl:' + detachvolurl);	
	invokeShutsimUrl('http://' + OpensimInstanceDnsName + ':9080/shutsim?' + detachvolurl, ShutSimStatus) 	
	
}
